package hedspi.k55.sm.view;

import java.io.InputStream;
import java.sql.Connection;
import java.util.Locale;

import hedspi.k55.sm.R;
import hedspi.k55.sm.model.Stock;
import android.R.bool;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.ActionBarSherlock.OnOptionsItemSelectedListener;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;

public class StockDetailActitivy extends SherlockActivity implements Iview {
	private ActionBar actionbar;
	private TextView lastTradedPrice;
	private TextView perfomanceText;
	private TextView lowText;
	private TextView low_52weekText;
	private TextView highText;
	private TextView high_52weekText;
	private TextView avg_vol;
	private TextView shares;
	private TextView betaText;
	private TextView delay;
	private TextView lastPriceTime;
	private TextView openText;
	private TextView volumeText;
	private TextView mktcapText;
	private TextView p_e;
	private TextView divyieldText;
	private TextView epsText;
	private TextView my_shares;
	private TextView avgPrice;
	private TextView annual;
	private TextView annual_perc;
	private ProgressBar progressbar;
	private ImageView chart;

	private Stock stock;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		setTheme(THEME);
		setContentView(R.layout.stock_detail_activity);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		// /////////////////////////////////////
		lastTradedPrice = (TextView) findViewById(R.id.stock_details_lastTradedPrice);
		perfomanceText = (TextView) findViewById(R.id.stock_details_perfomanceText);
		lastPriceTime = (TextView) findViewById(R.id.stock_details_lastPriceTime);
		openText = (TextView) findViewById(R.id.stock_details_openText);
		volumeText = (TextView) findViewById(R.id.stock_details_volumeText);
		mktcapText = (TextView) findViewById(R.id.stock_details_mktcapText);
		p_e = (TextView) findViewById(R.id.stock_details_peText);
		divyieldText = (TextView) findViewById(R.id.stock_details_divyieldText);
		epsText = (TextView) findViewById(R.id.stock_details_epsText);
		lowText = (TextView) findViewById(R.id.stock_details_lowText);
		low_52weekText = (TextView) findViewById(R.id.stock_details_low_52weekText);
		highText = (TextView) findViewById(R.id.stock_details_highText);
		high_52weekText = (TextView) findViewById(R.id.stock_details_high_52weekText);
		avg_vol = (TextView) findViewById(R.id.stock_details_avg_vol);
		shares = (TextView) findViewById(R.id.stock_details_shares);
		betaText = (TextView) findViewById(R.id.stock_details_betaText);
		delay = (TextView) findViewById(R.id.stock_details_delay);
		progressbar = (ProgressBar) findViewById(R.id.stock_detail_progressbar);
		chart = (ImageView) findViewById(R.id.stock_detail_chart_view);
		my_shares = (TextView) findViewById(R.id.stock_details_transaction_general_share_value);
		avgPrice = (TextView) findViewById(R.id.stock_details_transaction_general_avg_price_value);
		annual = (TextView) findViewById(R.id.stock_details_transaction_general_annual_value);
		annual_perc = (TextView) findViewById(R.id.stock_details_transaction_general_annual_perc_value);
		getContent();
		getSupportActionBar().setTitle(
				stock.getExchange().toUpperCase(Locale.ENGLISH) + ":"
						+ stock.getSymbol().toUpperCase(Locale.ENGLISH));
		setView(stock);
		// //////////////////////////////////

	}

	public void setView(Stock stock) {
		lastTradedPrice.setText(stock.getLastPrice());
		perfomanceText
				.setText(stock.getPercChange() + "% " + stock.getChange());
		lastPriceTime.setText(stock.getTradeTime());
		openText.setText(stock.getOpen());
		volumeText.setText(stock.getVolume());
		mktcapText.setText(stock.getMarketCap());
		p_e.setText(stock.getPE());
		epsText.setText(stock.getEPS());
		lowText.setText(stock.getLow());
		low_52weekText.setText(stock.getLow52week());
		highText.setText(stock.getHigh());
		high_52weekText.setText(stock.getHigh52week());
		avg_vol.setText(stock.getAvgVolume());
		shares.setText(stock.getShares());
		betaText.setText(stock.getBeta());
		String divyield = stock.getDividend() + "/" + stock.getDividendYield();
		if (divyield.length() != 1) {
			divyieldText.setText(divyield);
		}
		my_shares.setText(stock.getMyShares());
		avgPrice.setText(stock.getAvgPrice());
		annual.setText(stock.getAnnual() + "");
		annual_perc.setText(stock.getAnnaulPerc() + "");
		divyieldText.setHint("N/A");
		lastTradedPrice.setHint("N/A");
		perfomanceText.setHint("N/A");
		lastPriceTime.setHint("N/A");
		openText.setHint("N/A");
		volumeText.setHint("N/A");
		mktcapText.setHint("N/A");
		p_e.setHint("N/A");
		epsText.setHint("N/A");
		lowText.setHint("N/A");
		low_52weekText.setHint("N/A");
		highText.setHint("N/A");
		high_52weekText.setHint("N/A");
		avg_vol.setHint("N/A");
		shares.setHint("N/A");
		betaText.setHint("N/A");
		delay.setHint("Offline");
		if (isNetworkAvailable(getApplicationContext())) {
			delay.setText(R.string.real_time);
			progressbar.setVisibility(View.GONE);
			chart.setBackgroundColor(17170445);
			chart.setScaleType(ScaleType.FIT_XY);
			new DownloadImageTask(chart).execute(stock
					.getURLChart(Stock.ONE_WEEK));
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			break;
		default:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void getContent() {
		String symbol = getIntent().getStringExtra("symbol");
		stock = new Stock(this, symbol);
		stock.init();
		stock.refresh();
	}

	public boolean isNetworkAvailable(Context context) {
		try {
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo mobi = cm
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (wifi.isConnected() || mobi.isConnected())
				return true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
		ImageView bmImage;

		public DownloadImageTask(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Drawable doInBackground(String... urls) {
			String urldisplay = urls[0];
			Drawable drawable = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				drawable = Drawable.createFromStream(in, "chart");

			} catch (Exception e) {
				e.printStackTrace();
			}
			return drawable;
		}

		protected void onPostExecute(Drawable result) {
			bmImage.setImageDrawable(result);

		}
	}

}
